package 代码随想录.哈希;

import java.util.*;

public class a15三数之和 {
    static class Solution {
        public List<List<Integer>> threeSum0(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > 0) break;
                // 去重a
                if (i > 0 && nums[i - 1] == nums[i]) {
                    continue;
                }
                int left = i + 1;
                int right = nums.length - 1;
                while (left < right) {
                    if (nums[i] + nums[left] + nums[right] > 0) {
                        right--;
                    } else if (nums[i] + nums[left] + nums[right] < 0) {
                        left++;
                    } else {
                        res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                        // 去重 b
                        while (left < right && nums[left + 1] == nums[left]) {
                            left++;
                        }
                        // 去重 c
                        while (left < right && nums[right - 1] == nums[right]) {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
            return res;
        }

        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > 0) break;
                // 去重a
                if (i > 0 && nums[i - 1] == nums[i]) {
                    continue;
                }
                HashSet<Integer> set = new HashSet<>();
                for (int j = i + 1; j < nums.length; j++) {
                    // 去重b
                    if (j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2]) {
                        continue;
                    }
                    int c = -(nums[i] + nums[j]);
                    if (set.contains(c)) {
                        res.add(Arrays.asList(nums[i], nums[j], c));
                        // 去重c
                        set.remove(c);
                    }else{
                        set.add(nums[j]);
                    }
                }
            }
            return res;
        }
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = solution.threeSum(nums);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
